<template>
  <el-dialog title="分配菜单" v-model="dialogShow" width="650px">
    <div style="margin-top: 10px">
      <el-tree
        ref="treeRef"
        default-expand-all
        :data="props.treeParent"
        node-key="_id"
        :props="{ label: 'title' }"
        show-checkbox
      />
    </div>
    <el-divider style="margin-bottom: 0"></el-divider>
    <template #footer>
      <span>
        <el-button @click="cancel">取消</el-button>
        <el-button type="primary" @click="confirm">确认</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { updateRoleMenuApi } from '@/api/modules/role'
import { ElMessage, ElTree } from 'element-plus'
import { nextTick, ref, watch } from 'vue'

type Props = {
  treeParent: any
  roleData: any
}
const props = withDefaults(defineProps<Props>(), {
  treeParent: {
    type: Object,
    default: () => ({})
  },
  roleData: {
    type: Object,
    default: () => ({})
  }
})
const emit = defineEmits(['confirm', 'cancel'])
const treeRef = ref<InstanceType<typeof ElTree>>()
const dialogShow = ref(false)

// 监听roleData属性变化
watch(
  () => props.roleData,
  (val) => {
    nextTick(() => {
      if (val.menus) {
        treeRef.value?.setCheckedKeys(val.menus, false)
      }
    })
  },
  { immediate: true, deep: true }
)

const cancel = () => {
  dialogShow.value = false
  emit('cancel')
}

const confirm = async () => {
  const checkKeys = treeRef.value?.getCheckedKeys()
  const halfCheckedKeys = treeRef.value?.getHalfCheckedKeys()
  const res: any = await updateRoleMenuApi({
    params: {
      _id: props.roleData._id,
      menus: checkKeys,
      half_menus: halfCheckedKeys
    }
  })

  if (res.errCode === 0) {
    ElMessage.success('分配菜单成功！')
    dialogShow.value = false
    emit('confirm')
  }
}

const showDialog = () => {
  dialogShow.value = true
}

defineExpose({ showDialog })
</script>

<style lang="scss" scoped></style>
